import Food from './Food';
import ScorePanel from './ScorePanel';
import Snake from './Snake';

class GameControl {
    food: Food
    scorePanel: ScorePanel
    snake: Snake

    direction: string = ''

    islive: boolean = true

    constructor() {
        this.snake = new Snake()
        this.food = new Food()
        this.scorePanel = new ScorePanel(10, 2)

        this.init()
    }

    init() {
        document.addEventListener('keydown', this.keydownHandler.bind(this))
        this.run()

    }

    keydownHandler(event: KeyboardEvent) {
        this.direction = event.key
    }
    /**
     *  ArrowUp  Up
        ArrowDown Down
        ArrowLeft Left
        ArrowRight Right
     */
    run() {

        let X = this.snake.X
        let Y = this.snake.Y
        this.checkEate(X, Y)
        switch (this.direction) {
            case 'ArrowUp':
            case 'Up':
                Y -= 10
                break;
            case 'ArrowDown':
            case 'Down':
                Y += 10
                break;
            case 'ArrowLeft':
            case 'Left':
                X -= 10
                break;
            case 'ArrowRight':
            case 'Right':
                X += 10
                break;
        }

        try {
            this.snake.X = X
            this.snake.Y = Y
        } catch (e) {
            alert(e + ' GAME OVER!')
            this.islive = false
        }

        this.islive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30)
    }

    checkEate(X: number, Y: number) {
        if (X === this.food.X && Y === this.food.Y) {
            // 改变食物位置
            this.food.change()
            // 增加积分
            this.scorePanel.addScore()
            // 增加身体
            this.snake.addBody()
        }
    }
}

export default GameControl